package com.wsb.wetchat.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wang shaobo
 * @date 2022/6/17  16:53
 */
public class WetChatImg {

    public static final String CHAR_SET = "utf-8";
    public static final String TOKEN_API = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    public static final String MSG_SEND_API = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
    public static final String MEDIA_UPLOAD_API = "https://qyapi.weixin.qq.com/cgi-bin/media/upload";

    private CloseableHttpClient httpClient;
    private HttpPost httpPost;
    private HttpGet httpGet;


    public String upload(String fileType, String filePath, String token) throws Exception {
        // 返回结果
        String result = null;
        File file = new File(filePath);
        String name = file.getName();
        long length = file.length();
        String substring = name.substring(name.lastIndexOf(".") + 1);
        System.out.println(substring);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }

        String uploadUrl = MEDIA_UPLOAD_API + "?access_token=" + token + "&type=" + fileType;
        URL url = new URL(uploadUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// 以POST方式提交表单
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);// POST方式不能使用缓存
        // 设置请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        // 请求正文信息
        // 第一部分
        StringBuilder sb = new StringBuilder();
        sb.append("--");// 必须多两条道
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        // 获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        // 输出表头
        out.write(sb.toString().getBytes("UTF-8"));
        // 文件正文部分
        // 把文件以流的方式 推送道URL中
        DataInputStream din = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] buffer = new byte[1024];
        while ((bytes = din.read(buffer)) != -1) {
            out.write(buffer, 0, bytes);
        }
        din.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");// 定义数据最后分割线
        out.write(foot);
        out.flush();
        out.close();
        if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {

            StringBuffer strbuffer = null;
            BufferedReader reader = null;
            try {
                strbuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lineString = null;
                while ((lineString = reader.readLine()) != null) {
                    strbuffer.append(lineString);
                }
                if (result == null) {
                    result = strbuffer.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("media_id");
    }


    public String createImageData(String touser, int agentid, String media_id) {
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> image = new HashMap<String, Object>();
        data.put("touser", touser);
        data.put("toparty", "1");
        data.put("msgtype", "image");
        data.put("agentid", agentid);
        image.put("media_id", media_id);
        data.put("image", image);

        return JSONObject.toJSONString(data);
    }

    public String sendMsg(String data, String token) throws IOException {
        httpClient = HttpClients.createDefault();
        httpPost = new HttpPost(MSG_SEND_API + "?access_token=" + token);
        httpPost.setEntity(new StringEntity(data, CHAR_SET));
        CloseableHttpResponse res = httpClient.execute(httpPost);
        String resString;
        try {
            HttpEntity entity = res.getEntity();
            resString = EntityUtils.toString(entity, CHAR_SET);
            EntityUtils.consume(entity);
        } finally {
            res.close();
        }
        return resString;
    }



}
